package com.dongxing.concyrrency.chapter13;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class SimpleThreadPool extends Thread {


    private int size;
    private final int queueSize;

    private static final int DEFAULT_TASK_QUEUE_SIZE = 2000;

    private static volatile int seq = 0;

    private static final String THREAD_PREFIX = "SIMPLE_THREAD_POOL-";

    private static final ThreadGroup THREAD_GROUP = new ThreadGroup("Pool_Group");

    private static final LinkedList<Runnable> TASK_QUEUE = new LinkedList<>();

    private static final List<WorkTask> THREAD_QUEUE = new ArrayList<>();

    private final DiscardPolicy discardPolicy;

    public static final DiscardPolicy DEFAULT_DISCARD_POLICY = () -> {
        throw new DiscardException("Discard This Task.");
    };

    private volatile boolean destory = Boolean.FALSE;

    private int min;
    private int max;
    private int active;

    public SimpleThreadPool() {
        this(DEFAULT_TASK_QUEUE_SIZE, DEFAULT_DISCARD_POLICY, 4, 8, 12);
    }

    public SimpleThreadPool(int queueSize, DiscardPolicy discardPolicy, int min, int active, int max) {
        this.queueSize = queueSize;
        this.discardPolicy = discardPolicy;
        this.min = min;
        this.max = max;
        this.active = active;
        init();
    }

    private void init() {
//        for (int i = 0; i < size; i++) {
//            createWorkTest();
//        }
        for (int i = 0; i < this.min; i++) {
            createWorkTest();
        }
        this.size = min;
        this.start();
    }

    @Override
    public void run() {
        while (!destory) {
            System.out.printf("Pool# min:%d,Active:%d,Max:%d,Current:%d,QueueSize:%d\n",
                    this.min, this.active, this.max, this.size, TASK_QUEUE.size());

            try {
                TimeUnit.SECONDS.sleep(5);

                if (TASK_QUEUE.size() > active && size < active) {
                    // 扩容
                    for (int i = size; i < active; i++) {
                        createWorkTest();
                    }
                    System.out.println("The Pool incremented to active");
                    this.size = active;
                } else if (TASK_QUEUE.size() > max && size < max) {
                    for (int i = size; i < max; i++) {
                        createWorkTest();
                    }
                    System.out.println("The Pool incremented to max");
                    this.size = max;
                }
//                    防止submit的时候，添加东西
                synchronized (TASK_QUEUE) {
//                降低数量
                    if (TASK_QUEUE.isEmpty() && size > active) {

                        int releaseSize = (size - active);
                        for (Iterator<WorkTask> it = THREAD_QUEUE.iterator(); it.hasNext(); ) {
                            if (releaseSize <= 0) {
                                break;
                            }
                            WorkTask workTask = it.next();
                            workTask.close();
                            workTask.interrupt();
                            it.remove();
                            releaseSize--;
                        }
                        size = active;
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void createWorkTest() {
        WorkTask workTask = new WorkTask(THREAD_GROUP, THREAD_PREFIX + (seq++));
        workTask.start();
        THREAD_QUEUE.add(workTask);

    }


    public void shutdown() {

        // 无任务
        while (!TASK_QUEUE.isEmpty()) {
            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        synchronized (TASK_QUEUE) {
            // 线程全部是无用的状态
            int initVal = THREAD_QUEUE.size();
            while (initVal > 0) {
                for (WorkTask task : THREAD_QUEUE) {
                    if (task.getTaskState() == TaskState.BLOCKED) {
                        task.interrupt();
                        task.close();
                        initVal--;
                    } else {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

//        group中的可用的线程数
        System.out.println(THREAD_GROUP.activeCount());
        this.destory = true;
        System.out.println("The thread pool disposed.");
    }


    public int getSize() {
        return size;
    }

    public int getQueueSize() {
        return queueSize;
    }

    public Boolean isDestroy() {
        return this.destory;
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

    public int getActive() {
        return active;
    }

    public void submit(Runnable runnable) {

        if (destory)
            throw new IllegalStateException("The thread pool already destroy and not allow submit task");

        // 有读和有写的操作，所以需要加锁，来进行操作
        synchronized (TASK_QUEUE) {
            if (TASK_QUEUE.size() >= DEFAULT_TASK_QUEUE_SIZE)
                discardPolicy.discard();
            TASK_QUEUE.addLast(runnable);
            TASK_QUEUE.notifyAll();
        }
    }


    private enum TaskState {
        FREE, RUNNING, BLOCKED, DEAD
    }

    private static class DiscardException extends RuntimeException {
        public DiscardException(String message) {
            super(message);
        }
    }


    private interface DiscardPolicy {

        void discard() throws DiscardException;

    }

    private static class WorkTask extends Thread {

        private volatile TaskState taskState = TaskState.FREE;

        public WorkTask(ThreadGroup group, String name) {
            super(group, name);
        }

        public TaskState getTaskState() {
            return this.taskState;
        }

        public void run() {
            OUTER:
            // 线程没死
            while (this.taskState != TaskState.DEAD) {

                Runnable runnable;
                synchronized (TASK_QUEUE) {
                    // 没有任务
                    while (TASK_QUEUE.isEmpty()) {
                        try {
                            this.taskState = TaskState.BLOCKED;
                            TASK_QUEUE.wait();
                        } catch (InterruptedException e) {
                            break OUTER;
                        }
                    }
                    // 有执行任务
                    // 先进先出，保证顺序
                    runnable = TASK_QUEUE.removeFirst();
                }
                if (runnable != null) {
                    this.taskState = TaskState.RUNNING;
                    runnable.run();
                    this.taskState = TaskState.FREE;
                }
            }
        }

        public void close() {
            this.taskState = TaskState.DEAD;
        }


    }

    public static void main(String[] args) {
        SimpleThreadPool simpleThreadPool = new SimpleThreadPool();

        for (int i = 0; i < 40; i++) {
            simpleThreadPool.submit(() -> {
                System.out.println("The Runnable be serviced by " + Thread.currentThread() + " start");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("The Runnable be serviced by " + Thread.currentThread() + " finished.");
            });
        }

        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        simpleThreadPool.shutdown();
//        simpleThreadPool.submit(() -> System.out.println("==========="));
    }

}
